﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QNetworkInterface>
#include <QDateTime>
#include "common.h"
#include "Server.h"


MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    ui->editIP->setText(GetLocalIP());
    ui->editPort->setText(QString::number(FIR_SERVER_PORT));
    connect(Server::Instance(), &Server::sigLog, this, &MainWindow::slotLog);
//    on_btnStart_clicked();
}

MainWindow::~MainWindow()
{
    delete ui;
}

QString MainWindow::GetLocalIP()
{
    QList<QHostAddress> list = QNetworkInterface::allAddresses();
    foreach (QHostAddress address, list)
    {
       if(address.protocol() == QAbstractSocket::IPv4Protocol)
       {
           return address.toString();
       }
    }
    return "";
}

void MainWindow::AddLog(QString text)
{
    QString strTime = QDateTime::currentDateTime().toString("[yyyy/MM/dd HH:mm:ss]");
    ui->listWidget->addItem(strTime + " " + text);
}

void MainWindow::slotLog(QString text)
{
    AddLog(text);
}

void MainWindow::on_btnStart_clicked()
{
    bool bOK = false;
    int port = ui->editPort->text().toInt(&bOK);
    if(bOK)
    {
        if(Server::Instance()->Start(port))
        {
            AddLog(QStringLiteral("服务器启动成功！端口: %1").arg(port));
        }
        else
        {
            AddLog(QStringLiteral("服务器启动失败！端口: %1").arg(port));
        }
    }
    else
    {
        AddLog(QStringLiteral("请输入正确的端口号！"));
    }
}
